package com.qf.service.impl;

import com.qf.service.ContactExtractionService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 联系人提取服务实现
 *
 * @implNote 使用线程安全的模式存储
 * @since 9+
 */
@Service
public class ContactExtractionServiceImpl implements ContactExtractionService {

    private final List<Pattern> patterns = new CopyOnWriteArrayList<>();

    // 默认匹配规则 - 使用兼容方式初始化
    private static final List<String> DEFAULT_PATTERNS = createDefaultPatterns();

    private static List<String> createDefaultPatterns() {
        List<String> patterns = new ArrayList<>();
        patterns.add("联[\\s　]*系[\\s　]*人[\\s　]*[:：\\s]+([^<>\\[\\]{}()，。;；<br>]{2,20})");
        patterns.add("联系人[\\s　]*[:：\\s]+([^<>\\[\\]{}()，。;；<br>]{2,20})");
        patterns.add("项目联系人[\\s　]*[:：\\s]+([^<>\\[\\]{}()，。;；<br>]{2,20})");
        patterns.add("采购联系人[\\s　]*[:：\\s]+([^<>\\[\\]{}()，。;；<br>]{2,20})");
        patterns.add("联系人员[\\s　]*[:：\\s]+([^<>\\[\\]{}()，。;；<br>]{2,20})");
        return Collections.unmodifiableList(patterns);
    }

    public ContactExtractionServiceImpl() {
        resetToDefaultPatterns();
    }

    @Override
    public Optional<String> extractContact(String htmlContent) {
        if (htmlContent == null || htmlContent.trim().isEmpty()) {
            return Optional.empty();
        }

        String cleanText = cleanHtml(htmlContent);

        for (Pattern pattern : patterns) {
            Matcher matcher = pattern.matcher(cleanText);
            if (matcher.find()) {
                String contact = cleanContact(matcher.group(1));
                if (isValidContact(contact)) {
                    return Optional.of(contact);
                }
            }
        }

        return Optional.empty();
    }

    @Override
    public void addCustomPattern(String patternStr) {
        try {
            patterns.add(Pattern.compile(patternStr));
        } catch (Exception e) {
            throw new IllegalArgumentException("无效的正则表达式: " + patternStr, e);
        }
    }

    @Override
    public List<String> getPatterns() {
        return patterns.stream()
                .map(Pattern::pattern)
                .collect(Collectors.toList());
    }

    @Override
    public void resetToDefaultPatterns() {
        patterns.clear();
        DEFAULT_PATTERNS.forEach(this::addCustomPattern);
    }

    private String cleanHtml(String html) {
        return html.replaceAll("<[^>]+>", " ")
                .replaceAll("&nbsp;", " ")
                .replaceAll("\\s+", " ")
                .trim();
    }

    private String cleanContact(String contact) {
        return contact.trim()
                .split("[\\s，。;；]")[0]
                .replaceAll("[:：]", "");
    }

    private boolean isValidContact(String contact) {
        return contact != null &&
                contact.matches("^[\\u4e00-\\u9fa5]{2,6}$");
    }
}